package com.bus

import org.groovyflow.validation.*
import org.groovyflow.util.Rule
import org.groovyflow.util.Money


class PriceChangeValidations implements Validations{
    def doValidations(form, product){
        def v = new ObjectValidator(form)
        v.validations <<  ["increase", REQUIRED]
        v.validations <<  ["increase", MONEY_RULE]
        
        def negativeTotal = {prop, args ->
        	if(product.wouldBeNegative(args.obj.increase))
        		return " this change would result in a negative price"
        }
        v.validations <<  ["increase", negativeTotal]
       
        def noIncreaseErrors = {prop, args -> v.errors.increase == null }
        
        def noteConditionallyRequired = new Rule( pred : 
        	{prop, args ->  noIncreaseErrors(prop, args) &&  REQUIRED_PRED(prop, args) &&
        		(new Money(args.obj.increase)).ltZero() },
                action : {prop, args -> "comment required for price decrease"}
                )
        v.validations <<  ["note", noteConditionallyRequired]

        def highIncrease = new Rule( pred : 
        		{prop, args ->  noIncreaseErrors(prop, args) &&  
        			(new Money(args.obj.increase)).gt(new Money("20")) &&
        			! prop.startsWith("Sorry") },
        			action : { prop, args -> "Comment must start with 'Sorry' when increase > 20"}
            )        
        v.validations <<  ["note", highIncrease]
        
        v.validate()
        return v.errors

    }
} 